package com.xyxe.domain.strategy.service.rule.chain.factory;

import com.xyxe.domain.strategy.model.entity.StrategyEntity;
import com.xyxe.domain.strategy.repository.IStrategyRepository;
import com.xyxe.domain.strategy.service.rule.chain.ILogicChain;
import lombok.*;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 工厂
 */
@Service
public class DefaultChainFactory {
    private final Map<String, ILogicChain> logicChainMap;

    private final IStrategyRepository repository;

    public DefaultChainFactory(Map<String, ILogicChain> logicChainMap, IStrategyRepository repository) {
        this.logicChainMap = logicChainMap;
        this.repository = repository;
    }

    /**
     * 将责任结点按序组装并暴露出责任链首节点
     * @param strategyId
     * @return
     */
    public ILogicChain openLogicChain(Long strategyId) {
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        String[] ruleModels = strategyEntity.ruleModels();
        if (null == ruleModels || ruleModels.length == 0) return logicChainMap.get("default");

        ILogicChain chain = logicChainMap.get(ruleModels[0]);
        ILogicChain current = chain;
        for (int i = 1; i < ruleModels.length; i++) {
            ILogicChain logicChain = logicChainMap.get(ruleModels[i]);
            current = current.appendNext(logicChain);
        }
        current.appendNext(logicChainMap.get("default"));
        return chain;
    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class StrategyAwardVO {
        private Integer awardId;

        private String logicModel;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {
        RULE_DEFAULT("rule_default", "默认抽奖"),
        RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
        RULE_WEIGHT("rule_weight", "权重抽奖"),
        ;

        private final String code;
        private final String info;
    }
}
